package com.qiangesoft.ratelimit.core;

import com.qiangesoft.ratelimit.utils.IpUtil;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.springframework.util.Assert;

import java.util.Objects;

/**
 * 限流key构建工具
 *
 * @author qiangesoft
 * @date 2024-02-27
 */
@Data
public class LimitKeyBuilder {

    private static final String RATE_PREFIX = "rate_limit:";

    public static String build(LimitType limitType, String key, JoinPoint joinPoint) {
        Assert.notNull(limitType, "limitType is not null");
        if (StringUtils.isBlank(key)) {
            String targetName = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            key = targetName + "." + methodName;
        }
        key = RATE_PREFIX + key;
        if (LimitType.IP == limitType) {
            key = key + "-" + IpUtil.getIpAddr();
        }
        return key;
    }
}
